//
//  daizhifuVC.m
//  YaoHeAPP
//
//  Created by xyh on 16/4/11.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "daizhifuVC.h"

#import "Masonry.h"

#import "Controller.h"

#import "SVPullToRefresh.h"

#import "daizhifuHeaderView.h"
#import "orderfooterView.h"

#import "labelview.h"

#import "MyOrderData.h"
#import "MyorderDataList.h"

#import "orderCell.h"


#import "TongYong.h"


#import "moneybuyCV.h"

#import "TWOstuDetailsVC.h"
#import "NSString+formatWithFloat.h"

#define bgVCcolor [UIColor colorWithRed:235.f/255.f green:235.f/255.f blue:244.f/255.f alpha:1]
#define Color153  [UIColor colorWithRed:80.f/255.f green:80.f/255.f blue:80.f/255.f alpha:1]
#define screenWidth self.view.frame.size.width
#define screenHeight self.view.frame.size.height



@interface daizhifuVC ()<UITableViewDelegate,UITableViewDataSource,moneybuyCVdelgaet>
{
    NSMutableArray *arrayList;//总数组
    
    NSMutableArray *orderCellArray;//内部表格
    
    labelview *la;

    //是否全选
    NSString *isQX;
    
    
    UIButton *quanxuanBUt;//全选按钮
    UIButton *jiesuanBUt;//结算按钮
    
    UILabel *hejiMoney;//合计金额
    UILabel *heji;//合计
    UILabel *qx;//全选

    NSMutableArray *totalLastTime;
    
    NSTimer *timer;

    NSInteger quxiaosectionbut;

    UIView *bootmView;
    
}
@property(nonatomic,strong) UITableView *tableview;
@property (nonatomic, assign)NSInteger  page;//页数
@end

@implementation daizhifuVC

//视图将要消失的时候将定时器关闭
- (void)viewDidDisappear:(BOOL)animated {
    if (timer.isValid) {
        [timer invalidate];
    }
    timer=nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"daizhifuVC"];
    
    [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
    
    [self insertRowAtTop];
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"daizhifuVC"];
    
    [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //注册一个通知监听通知过来的操作  
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(updaizhifuorderview) name:@"daizhifuorderlist" object:nil];

    
    self.navigationController.navigationBar.hidden=YES;
    
    self.view.backgroundColor=bgVCcolor;
    //加一个导航条
    UIView*navcBar=[[UIView alloc]init];
    navcBar.backgroundColor=[UIColor colorWithRed:90.f/255.f green:191.f/255.f blue:219.f/255.f alpha:1];
    [self.view addSubview:navcBar];
    [self.view bringSubviewToFront:navcBar];
    //    navcBar.frame=CGRectMake(0, 0, screenWidth, 60);
    [navcBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);   make.left.offset(0);
        make.height.offset(kNavigationBarHeight);  make.right.offset(0);
    }];
    //导航条标题
    UILabel*titleLabel=[[UILabel alloc]init];
    titleLabel.text=@"待支付订单";
    titleLabel.font=Font(17);
    titleLabel.textAlignment=NSTextAlignmentCenter;
    titleLabel.textColor=[UIColor whiteColor];
    [navcBar addSubview:titleLabel];
    //    titleLabel.frame=CGRectMake(self.view.frame.size.width/2-70, 25, 140, 30);
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(25);
        make.left.offset(self.view.frame.size.width/2-70);
        make.width.offset(140);
        make.height.offset(30);
    }];
    
    //返回按钮
    UIButton*leftButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backLogin) forControlEvents:UIControlEventTouchUpInside];
    [navcBar addSubview:leftButton];
    //    leftButton.frame=CGRectMake(6, 60-6-28, 30, 28);
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(6);
        make.width.offset(24);
        make.height.offset(22);
        make.bottom.offset(-12);
    }];
    
    
    
    //定义数组
    arrayList=[[NSMutableArray alloc]init];
    orderCellArray=[[NSMutableArray alloc]init];
    totalLastTime=[[NSMutableArray alloc]init];
    //创建表格
    _tableview=[[UITableView alloc]initWithFrame:CGRectMake(0,kNavigationBarHeight, self.view.frame.size.width, self.view.frame.size.height-kNavigationBarHeight-50) style:UITableViewStyleGrouped];
    
    _tableview.backgroundColor= [UIColor colorWithRed:230/255.0 green:232/255.0 blue:241/255.0  alpha:1];
    _tableview.delegate=self;
    _tableview.dataSource=self;
    _tableview.separatorStyle=NO;
    
    [self.view addSubview:_tableview];
    
    
    //放置下拉上拉刷新控件
    __weak daizhifuVC *weakSelf = self;
    
    // setup pull-to-refresh
    [self.tableview addPullToRefreshWithActionHandler:^{
        [weakSelf insertRowAtTop];
    }];
    
    // setup infinite scrolling
    [self.tableview addInfiniteScrollingWithActionHandler:^{
        [weakSelf insertRowAtBottom];
    }];
    
    
    

    
    //下部按钮
    bootmView=[[UIView alloc]init];
    bootmView.backgroundColor=[UIColor whiteColor];
    bootmView.frame=CGRectMake(0,screenHeight-50, screenWidth, 50);
    [self.view addSubview:bootmView];
    
    
    isQX=@"false";
    
    //全部选择按钮
    quanxuanBUt=[UIButton buttonWithType:UIButtonTypeCustom];
    [quanxuanBUt setBackgroundImage:[UIImage imageNamed:@"ic_radio_btn_normal"] forState:UIControlStateNormal];
    [quanxuanBUt addTarget:self action:@selector(quanxuanBUtAction) forControlEvents:UIControlEventTouchUpInside];
    quanxuanBUt.frame=CGRectMake(10, 12.5, 25, 25);
    quanxuanBUt.layer.masksToBounds=YES;
    quanxuanBUt.layer.cornerRadius=12.5;
    [bootmView addSubview:quanxuanBUt];
    
    qx=[[UILabel alloc]init];
    qx.frame=CGRectMake(40, 10, 40, 30);
    qx.text=@"全选";
    qx.font=[UIFont systemFontOfSize:14];
    [bootmView addSubview:qx];
    
    
    //金额
    hejiMoney=[[UILabel alloc]init];
    hejiMoney.frame=CGRectMake(screenWidth-200, 10, 120, 30);
    hejiMoney.textColor=[UIColor colorWithRed:251.f/255.f green:87.f/255.f blue:60.f/255.f alpha:1];
    hejiMoney.text=@"￥0元";
    hejiMoney.font=[UIFont systemFontOfSize:14];
    [bootmView addSubview:hejiMoney];
    //合计：
    heji=[[UILabel alloc]init];
    heji.frame=CGRectMake(screenWidth-240, 10, 40, 30);
    heji.text=@"合计:";
    heji.font=[UIFont systemFontOfSize:14];
    [bootmView addSubview:heji];
    
    
    //结算
    jiesuanBUt=[[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width-80,1, 80, 50)];
    jiesuanBUt.backgroundColor=[UIColor colorWithRed:251.f/255.f green:87.f/255.f blue:60.f/255.f alpha:1];
    [jiesuanBUt setTitle:@"结算" forState:UIControlStateNormal];
    jiesuanBUt.titleLabel.font=[UIFont systemFontOfSize:14];
    [jiesuanBUt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [jiesuanBUt addTarget:self action:@selector(jiesuanBUtAction) forControlEvents:UIControlEventTouchUpInside];
    [bootmView addSubview:jiesuanBUt];
    jiesuanBUt.hidden=NO;

    
    
}
//通知返回刷新数据
-(void)updaizhifuorderview
{

[self insertRowAtTop];
    

}


#pragma mark -----------------按钮点击事件--------------------------
//全选按钮
-(void)quanxuanBUtAction
{
    //全部选中
    
    if ([isQX isEqualToString:@"true"]) {
        
        isQX=@"false";
        
        for (int i=0; i<arrayList.count; i++) {
            
           [arrayList[i] setObject:@"false" forKey:@"isSelected"];
            
        }
        
        
    }else{
        
        isQX=@"true";
        
        for (int i=0; i<arrayList.count; i++) {
            
            [arrayList[i] setObject:@"true" forKey:@"isSelected"];
            
        }
        
    }
    
    [self.tableview reloadData];
    
    [self loadBottomView];
    
}
//结算按钮
-(void)jiesuanBUtAction
{
    [MobClick event:@"daizhifuliebiao_piliangzhifu"];
    
    NSMutableArray *productIDarray=[[NSMutableArray alloc]init];
    NSInteger time = INT64_MAX;
    for (int i=0; i<arrayList.count; i++) {
        
        MyOrderData *dat=[[MyOrderData alloc]initWith:arrayList[i]];
        
        if ([dat.isSelected isEqualToString:@"true"]) {
            
            [productIDarray addObject:dat.intent_order_id];
            //获取选中状态单子的最小时间
            NSInteger time1 = dat.expired_time.integerValue;
            if (time1<time) {
                time=time1;
            }
            
        }

    }
    
    NSString *string = [productIDarray componentsJoinedByString:@","];

    if (productIDarray.count>0) {
    
    moneybuyCV *moneyvc=[[moneybuyCV alloc]init];
    moneyvc.ordernum=productIDarray.count;
    moneyvc.pay_type=@"10";
    moneyvc.intent_order_id=string;
    moneyvc.delegate=self;
        
        
   //获取当前时间值
    NSTimeInterval timest = [[NSDate date] timeIntervalSince1970];
    NSInteger timeintage=timest;
    NSInteger extime=time/1000;
    NSInteger timevely=timeintage+extime;
    moneyvc.odertime=[NSString stringWithFormat:@"%ld",(long)timevely];
        
    [self.navigationController pushViewController:moneyvc animated:YES];
        
    }

}



-(void)insertRowAtTop {
    __weak daizhifuVC *weakSelf = self;
    
    [weakSelf.tableview beginUpdates];
     _page=0;
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    [dic setValue:@"0" forKey:@"page_num"];
    [dic setValue:@"10" forKey:@"page_step"];
    
    [Controller requestWithURL:NeedPayOderlist jsondic:dic finishBlock:^(ClassData* data) {
        if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
        {
            
            NSMutableArray *mua=[NSMutableArray array];
            
            mua=data.data[@"data"];
            
            [arrayList removeAllObjects];
            
            [totalLastTime removeAllObjects];
            
            for (int i=0; i<mua.count; i++) {
                
                NSMutableDictionary *sd=[[NSMutableDictionary alloc]init];
                sd=mua[i];
                sd=[sd mutableCopy];
                [sd setValue:@"false" forKey:@"isSelected"];
                
                //                [arrayList addObject:sd];
                
                NSString *miaost=sd[@"expired_time"];
                NSInteger miao=miaost.integerValue/1000;
                
                //1.现根据毫秒数来判断是不是为负的
                
                if (miao>0) {
                    
                    [arrayList addObject:sd];
                    
                }
                
            }
            
            
            for (int i=0; i<arrayList.count; i++) {
                
                NSString *miaost=arrayList[i][@"expired_time"];
                NSInteger miao=miaost.integerValue/1000;
                NSString *stm=[NSString stringWithFormat:@"%ld",(long)miao];
                
                NSDictionary *dic = @{@"indexPath":[NSString stringWithFormat:@"%i",i],@"lastTime":stm};
                [totalLastTime addObject:dic];
                
            }

            //判断 是否  有 无数据
            if (arrayList.count==0) {
                if (la) {
                    [la removeFromSuperview];
                }
                la=[[labelview alloc]init];
                [la setimage:@"dingdanNew" tit:@"暂无订单数据" buttontit:nil frem:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
                la.backgroundColor= [UIColor colorWithRed:230/255.0 green:232/255.0 blue:241/255.0  alpha:1];
                la.image.frame=CGRectMake((self.view.frame.size.width-100)/2, 50, 100, 133);
                la.label.frame=CGRectMake(50, 193, self.view.frame.size.width-100, 30);
                [_tableview addSubview:la];
                bootmView.hidden=YES;
                

            }else{
                
                if (la) {
                    [la removeFromSuperview];
                }
                
                [self.tableview reloadData];
                
                [self loadBottomView];
                
                if (totalLastTime.count>0) {
                    
                    [self startTimer];
                }
                
            }
            
        }
        else
        {
            
        }
    }];
    
    // 3. 结束刷新(相当于动画)
    [weakSelf.tableview endUpdates];
    
    
    [weakSelf.tableview.pullToRefreshView stopAnimating];
    
    
}


- (void)insertRowAtBottom {
    
    __weak daizhifuVC *weakSelf = self;
    
    [weakSelf.tableview beginUpdates];
    
    
    _page=_page+1;
    NSNumber*number1=[NSNumber numberWithInteger:_page];
    NSNumber*number2=[NSNumber numberWithInteger:10];
    
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    [dic setValue:number1 forKey:@"page_num"];
    [dic setValue:number2 forKey:@"page_step"];
     [Controller requestWithURL:NeedPayOderlist jsondic:dic finishBlock:^(ClassData* data) {
        if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
        {
            NSMutableArray *mua=[NSMutableArray array];
            mua=data.data[@"data"];
            for (int i=0; i<mua.count; i++) {
                NSMutableDictionary *sd=[[NSMutableDictionary alloc]init];
                sd=mua[i];
                sd=[sd mutableCopy];
                [sd setValue:@"false" forKey:@"isSelected"];
                NSString *miaost=sd[@"expired_time"];
                NSInteger miao=miaost.integerValue/1000;
                //1.现根据毫秒数来判断是不是为负的
                if (miao>0) {
                    [arrayList addObject:sd];
                }
            }
            
            for (int i=0; i<arrayList.count; i++) {
                
                NSString *miaost=arrayList[i][@"expired_time"];
                NSInteger miao=miaost.integerValue/1000;
                miao=10;
                NSString *stm=[NSString stringWithFormat:@"%ld",(long)miao];
                
                NSDictionary *dic = @{@"indexPath":[NSString stringWithFormat:@"%i",i],@"lastTime":stm};
                [totalLastTime addObject:dic];
                
            }

            
            [self.tableview reloadData];
            if (totalLastTime.count>0) {
                
                [self startTimer];
            }

            
        }
        else
        {
            
        }
    }];
    
    [weakSelf.tableview endUpdates];
    [weakSelf.tableview.infiniteScrollingView stopAnimating];
    
}

#pragma mark ------------开启定时器方法--------
//开启定时器方法：
- (void)startTimer
{
    //将其注销重新开始
    if (timer.isValid) {
        [timer invalidate];
    }
    
    timer=nil;
    
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshLessTime) userInfo:@"" repeats:YES];
    
    //    如果不添加下面这条语句，在UITableView拖动的时候，会阻塞定时器的调用
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
    
}

//主要的定时器中的方法，在该方法中，遍历totalLastTime，取出其中保存的lasttime和indexpath，time用来显示，在显示完后自减，indexpath代表对应显示的位置，在一次循环后，将新的time和没有改变的indexpath从新替换totalLastTime 中对应位置的元素，以此保证每一秒执行时，显示time都是最新的。
- (void)refreshLessTime
{
    NSInteger time;
    for (int i = 0; i < totalLastTime.count; i++) {
        time = [[[totalLastTime objectAtIndex:i] objectForKey:@"lastTime"] integerValue];
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:[[[totalLastTime objectAtIndex:i] objectForKey:@"indexPath"] integerValue]];
        
        if (time<0) {
            //刷新并移除过时的数据
            [self insertRowAtTop];
            
        }else{
            
            orderfooterView *footview = (orderfooterView *)[_tableview footerViewForSection:indexPath.section];
            NSString *ss=[NSString stringWithFormat:@"截止时间:%@",[self lessSecondToDay:--time]];
            NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:ss];
            NSRange redRange = NSMakeRange([[noteStr string] rangeOfString:@":"].location+1,noteStr.length-5 );
            [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:redRange];
            [footview.jiezhiTime setAttributedText:noteStr] ;
            
            NSDictionary *dic = @{@"indexPath": [NSString stringWithFormat:@"%li",(long)indexPath.section],@"lastTime": [NSString stringWithFormat:@"%lu",(unsigned long)time]};
            [totalLastTime replaceObjectAtIndex:i withObject:dic];
            
        }
        
        
    }
}

- (NSString *)lessSecondToDay:(NSUInteger)seconds
{
    //    NSUInteger day  = (NSUInteger)seconds/(24*3600);
    NSUInteger hour = (NSUInteger)(seconds%(24*3600))/3600;
    NSUInteger min  = (NSUInteger)(seconds%(3600))/60;
    NSUInteger second = (NSUInteger)(seconds%60);
    
    NSString *time = [NSString stringWithFormat:@"%lu:%lu:%lu",(unsigned long)hour,(unsigned long)min,(unsigned long)second];
    return time;
    
}





#pragma  mark--------------表格代理方法-----------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return arrayList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    MyOrderData *order=[[MyOrderData alloc]initWith:arrayList[section]];
    
    return order.pro_data.count;
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //指定cellIdentifier为自定义的cell
    static NSString *CellIdentifier = @"orderCell";
    
    //取出对应段落的数据
    MyOrderData *order3=[[MyOrderData alloc]initWith:arrayList[indexPath.section]];
    
    MyorderDataList *orderListData=[[MyorderDataList alloc]initWith:order3.pro_data[indexPath.row]];
    
    //自定义cell类
    orderCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    //无色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (cell == nil) {
        //通过xib的名称加载自定义的cell
        cell = [[[NSBundle mainBundle] loadNibNamed:@"orderCell" owner:self options:nil] lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    //    4.1.1订单列表：展示货品参数
    //    展示购买的货品：
    //    型材 、管材 ： 品类（如扁钢等）、 材质、 规格、形状（如方管、圆管等，客户没有上传就不展示）、重量（总重）、数量、所在地、产地；
    //    卷、板、带：材质、表面、 规格(厚度*宽度*长度） 参厚 等级 重量（总重） 仓库、产地；
    
    
    //顶部字符串拼接
    NSString *toplable;
    if ([TongYong isBlankObjectAndStr:orderListData.suface_code]) {
        toplable=[NSString stringWithFormat:@"%@ %@",orderListData.category_name,orderListData.material_code];
    }else{
        toplable=[NSString stringWithFormat:@"%@ %@/%@",orderListData.category_name,orderListData.material_code,orderListData.suface_code];
        
    }
    
    
    
    NSString *guige=orderListData.spec_code;
    
    //参厚
    NSString *canhou;
    if ([TongYong isBlankObjectAndStr:orderListData.reference_thick ]) {
        canhou=@"";
    }else{
        canhou=[NSString stringWithFormat:@"(%@)",orderListData.reference_thick];
    }
    
    //边部
    NSString *bianbu;
    if ([TongYong isBlankObjectAndStr:orderListData.edge_name ]) {
        bianbu=@"";
    }else{
        
        bianbu=[NSString stringWithFormat:@"/%@",orderListData.edge_name];
        
    }
    
    //等级
    NSString *dengji;
    if ([TongYong isBlankObjectAndStr:orderListData.level_name ]) {
        
        dengji=@"";
        
    }else{
        
        dengji=[NSString stringWithFormat:@"/%@",orderListData.level_name];
        
    }
    
    
    //包装
    NSString *baozhuang;
    if ([TongYong isBlankObjectAndStr:orderListData.package_type ]) {
        
        baozhuang=@"";
        
    }else{
        //包装类型//(30,"裸包"),(10,"简包"),(20,"精包"),(0,"正常包装")
        NSInteger typ=orderListData.package_type.integerValue;
        if (typ==30) {
            baozhuang=[NSString stringWithFormat:@"/裸包"];
        }else if(typ==20){
            baozhuang=[NSString stringWithFormat:@"/精包"];
        }else if(typ==10){
            baozhuang=[NSString stringWithFormat:@"/简包"];
        }else{
            
            baozhuang=[NSString stringWithFormat:@"正常包装"];
        }
    }
    
    
    //形状
    NSString *xinzhuang;
    if ([TongYong isBlankObjectAndStr:orderListData.shape_name ]) {
        
        xinzhuang=@"";
        
    }else{
        
        xinzhuang=[NSString stringWithFormat:@"/%@",orderListData.shape_name];
        
    }
    
    //品名
    NSString *pingming;
    if ([TongYong isBlankObjectAndStr:orderListData.category_name ]) {
        
        pingming=@"";
        
    }else{
        
        pingming=[NSString stringWithFormat:@"/%@",orderListData.category_name];
        
    }
    
    
    //单位类型
    NSInteger unitpric=orderListData.price_unit.integerValue;
    //并计算出金额
    //计算金额
    //单位类型
    NSString *QUANTITY=[NSString stringWithFormat:@"%@",orderListData.quantity];
    NSString *weight=[NSString stringWithFormat:@"%@",orderListData.weight];
    //    NSString *sale_price=[NSString stringWithFormat:@"%@",orderListData.DISCOUNT_PRICE];
    
    NSDecimalNumber *quantityDM = [[NSDecimalNumber alloc] initWithString:QUANTITY];//个数
    NSDecimalNumber *weightDM = [[NSDecimalNumber alloc] initWithString:weight];//单个重量
    
    NSDecimalNumber *zongweightDM=[[NSDecimalNumber alloc]initWithString:@"0"];
    
    NSString *weightName;
    if (unitpric==10) {
        //元每吨
        NSDecimalNumber *qian = [[NSDecimalNumber alloc] initWithString:@"1000"];
        zongweightDM = [quantityDM decimalNumberByMultiplyingBy:weightDM];
        zongweightDM=[zongweightDM decimalNumberByDividingBy:qian];
        weightName=[NSString stringWithFormat:@"/%@吨/%ld",[NSString notRounding:zongweightDM afterPoint:3],(long)orderListData.quantity.integerValue];
    } else if (unitpric==20||unitpric==40) {
        //支或张
        zongweightDM = [quantityDM decimalNumberByMultiplyingBy:weightDM];
        weightName=[NSString stringWithFormat:@"/%@千克/%ld",[NSString notRounding:zongweightDM afterPoint:3],(long)orderListData.quantity.integerValue];
    } else {
        //千克
        zongweightDM = [quantityDM decimalNumberByMultiplyingBy:weightDM];
        weightName=[NSString stringWithFormat:@"/%@千克/%ld",[NSString notRounding:zongweightDM afterPoint:3],(long)orderListData.quantity.integerValue];
    }

    NSString *bigTEXT;
    if ([orderListData.category_name isEqualToString:@"板"]||[orderListData.category_name isEqualToString:@"卷"]||[orderListData.category_name isEqualToString:@"板材"]||[orderListData.category_name isEqualToString:@"卷材"]) {
        //		板卷   规格(参厚)/边部/等级/包装
        
        bigTEXT=[NSString stringWithFormat:@"%@  %@%@%@%@%@%@",toplable,guige,canhou,bianbu,dengji,weightName,baozhuang];
        
        
    }else{
        
        bigTEXT=[NSString stringWithFormat:@"%@  %@%@%@%@%@%@%@",toplable,guige,pingming,xinzhuang,bianbu,dengji,weightName,baozhuang];
    }
    
    cell.bigLable.text=bigTEXT;
    
    
    //仓库  生产商
    NSString *ck;
    if ([TongYong isBlankObjectAndStr:orderListData.house_name ]) {
        
        ck=@"";
        
    }else{
        
        ck=[NSString stringWithFormat:@"%@",orderListData.house_name];
        
    }
    
    NSString *scs;
    if ([TongYong isBlankObjectAndStr:orderListData.manufacturer_name ]) {
        
        scs=@"";
        
    }else{
        
        scs=[NSString stringWithFormat:@"%@",orderListData.manufacturer_name];
        
    }
    
    cell.addandhous.text=[NSString stringWithFormat:@"%@    %@",ck,scs];
    
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MyOrderData *orderdetail=[[MyOrderData alloc]initWith:arrayList[indexPath.section]];
    
    TWOstuDetailsVC *generalVC=[[TWOstuDetailsVC alloc]init];
    generalVC.intent_order_id=orderdetail.intent_order_id;
    generalVC.isdaizhifu=@"待支付列表";
    [self.navigationController pushViewController:generalVC animated:YES];
}
#pragma mark -----------------设置段头段尾--------------------------
//区头高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}
//返回区头View
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    MyOrderData *order2=[[MyOrderData alloc]initWith:arrayList[section]];
    
    
    daizhifuHeaderView *headView=[[daizhifuHeaderView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 40)];
    
    
    [headView.selectButton addTarget:self action:@selector(selectButton:) forControlEvents:UIControlEventTouchUpInside];

    headView.selectButton.tag=section+100;
    
    
    if ([order2.isSelected isEqualToString:@"true"]) {
        
        [headView.selectButton setBackgroundImage:[UIImage imageNamed:@"ic_apply_quality_selected"] forState:UIControlStateNormal];
    }else{
        
        [headView.selectButton setBackgroundImage:[UIImage imageNamed:@"ic_radio_btn_normal"] forState:UIControlStateNormal];
    }

    
    
    headView.contentView.backgroundColor=[UIColor colorWithRed:230/255.0 green:232/255.0 blue:241/255.0  alpha:1];
    
    NSString *stheaderla;
    NSString *statustr;
    //现货订单号
    stheaderla=[NSString stringWithFormat:@"%@",order2.intent_order_code];
    statustr=@"待支付";
    
    headView.companyorderlabel.text=stheaderla;
    headView.orderstaylabel.text=statustr;
    return headView;
}

//用区尾当分割
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 34;
    
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    
    MyOrderData *order4=[[MyOrderData alloc]initWith:arrayList[section]];
    
    orderfooterView *footerView=[[orderfooterView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 34)];
    
    footerView.contentView.backgroundColor=[UIColor whiteColor];
    
    //判断是哪来的订单
    if (order4.source_flag.integerValue==0) {
        //现货订单号
        
        NSInteger status=order4.status.integerValue;
        
        if (status==10) {
            //            statustr=@"待支付";
            //            （取消订单）（去支付）
            footerView.leftbutton.layer.borderWidth=1;
            footerView.leftbutton.layer.borderColor=[UIColor colorWithRed:193/255.0 green:193/255.0 blue:193/255.0  alpha:1].CGColor;
            footerView.leftbutton.backgroundColor=[UIColor whiteColor];
            footerView.leftbutton.tag=10000+section;
            [footerView.leftbutton setTitle:@"取消订单" forState:UIControlStateNormal];
            footerView.leftbutton.titleLabel.font=[UIFont systemFontOfSize:14];
            [footerView.leftbutton setTitleColor:[UIColor colorWithRed:80/255.0 green:84/255.0 blue:85/255.0  alpha:1] forState:UIControlStateNormal];
            [footerView.leftbutton addTarget:self action:@selector(leftbuttonAction:) forControlEvents:UIControlEventTouchUpInside];
            
            
            
            footerView.rightbutton.backgroundColor=[UIColor colorWithRed:251/255.0 green:87/255.0 blue:60/255.0  alpha:1];
            [footerView.rightbutton setTitle:@"去支付" forState:UIControlStateNormal];
            footerView.rightbutton.tag=20000+section;
            footerView.rightbutton.titleLabel.font=[UIFont systemFontOfSize:14];
            [footerView.rightbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [footerView.rightbutton addTarget:self action:@selector(rightbuttonAction:) forControlEvents:UIControlEventTouchUpInside];
            
            
        }
        
        
        
    }
    
//    NSInteger miao=order4.expired_time.integerValue;
    
//    NSString *ss=[NSString stringWithFormat:@"截止时间:18：16分"];
//    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:ss];
//    NSRange redRange = NSMakeRange([[noteStr string] rangeOfString:@":"].location+1,noteStr.length-5 );
//    [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:redRange];
//    [footerView.jiezhiTime setAttributedText:noteStr] ;
    
//    footerView.jiezhiTime.text=@"截止时间:18：16";
    
    return footerView;
    
}


#pragma mark------------尾部按钮事件-----------------
//左边按钮事件
-(void)leftbuttonAction:(UIButton *)leghtbut
{
    NSInteger tagbut=leghtbut.tag;
    
    NSInteger butsection=tagbut-10000;
    
    MyOrderData *order5=[[MyOrderData alloc]initWith:arrayList[butsection]];
    
    //判断是哪来的订单
    if (order5.source_flag.integerValue==0) {
        //现货订单号
        NSInteger status=order5.status.integerValue;
        
        if (status==10) {
            //            statustr=@"待支付";    （取消订单）
            [self quxiaoorder:butsection];
            
        }
        
    }
    
    
    
}

//右边按钮事件
-(void)rightbuttonAction:(UIButton *)rightbut
{
    NSInteger tagbut=rightbut.tag;
    
    NSInteger butsection=tagbut-20000;
    
    
    MyOrderData *order6=[[MyOrderData alloc]initWith:arrayList[butsection]];
    
    //判断是哪来的订单
    if (order6.source_flag.integerValue==0) {
        //现货订单号
        NSInteger status=order6.status.integerValue;
        
        if (status==10) {
            //            statustr=@"待支付";     （去支付）
            [self quzhifu:butsection];
            
        }
        
    }
    

}

//取消订单
-(void)quxiaoorder:(NSInteger )sectionbut
{
    
    
    quxiaosectionbut=sectionbut;
    
    //初始化AlertView
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"取消订单"
                                                    message:@"订单取消后无法恢复，确定要取消订单吗？"
                                                   delegate:self
                                          cancelButtonTitle:@"取消"
                                          otherButtonTitles:@"确定",nil];
    
    //这个属性继承自UIView，当一个视图中有多个AlertView时，可以用这个属性来区分
    alert.tag = 4;
    //只读属性，看AlertView是否可见
    [alert show];
    
}
//根据被点击按钮的索引处理点击事件
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
      if(alertView.tag==4){
        
        if (buttonIndex==1) {
            //呼叫客服
            
            MyOrderData *order7=[[MyOrderData alloc]initWith:arrayList[quxiaosectionbut]];
            
            NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
            [dic setValue:order7.intent_order_id forKey:@"intent_order_id"];
            [Controller requestWithURL:CANCELORDER jsondic:dic finishBlock:^(ClassData* data) {
                if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
                {
                    //刷新列表
                    [self insertRowAtTop];
                    
                }
                else
                {
                    
                }
            }];
            
            
            
        }
        
    }
    
    
}


//去支付
-(void)quzhifu:(NSInteger )sectionbut
{
    
    [MobClick event:@"daizhifuliebiao_dangezhifu"];
    
    MyOrderData *order7=[[MyOrderData alloc]initWith:arrayList[sectionbut]];
    
    moneybuyCV *moneyvc=[[moneybuyCV alloc]init];
    moneyvc.pay_type=@"10";
    moneyvc.intent_order_id=order7.intent_order_id;
    moneyvc.ordernum=1;
    moneyvc.delegate=self;
    //获取当前时间值
    NSTimeInterval timest = [[NSDate date] timeIntervalSince1970];
    
    NSInteger timeintage=timest;
    
    NSString *sttime=order7.expired_time;
    
    NSInteger extime=sttime.integerValue/1000;
    
    NSInteger timevely=timeintage+extime;
    
    moneyvc.odertime=[NSString stringWithFormat:@"%ld",(long)timevely];

    [self.navigationController pushViewController:moneyvc animated:YES];

    
    
}
//支付成功刷新界面
-(void)uporderlist
{
    [self insertRowAtTop];
    
}


-(void)backLogin
{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

//区头公司圆圈的点击事件
-(void)selectButton:(UIButton*)quTou
{
    
    //    UITableViewHeaderFooterView * cell = (UITableViewHeaderFooterView *)[[quTou superview] superview];
    //    NSIndexSet *indexPath = [self.tableview indexPathForRowAtPoint:<#(CGPoint)#>];
    MyOrderData *order8=[[MyOrderData alloc]initWith:arrayList[quTou.tag-100]];
    
    if ([order8.isSelected isEqualToString:@"false"]) {
        
       [arrayList[quTou.tag-100] setObject:@"true" forKey:@"isSelected"];
        
    }else{
        
        [arrayList[quTou.tag-100] setObject:@"false" forKey:@"isSelected"];
        
    }
    
    //刷新某一段
    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:quTou.tag-100];
    [self.tableview reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
    
    [self loadBottomView];
    
}

-(void)loadBottomView
{

    
    //这里面分3步，1.全选按钮是否被选中  2.总共多少元     3.结算了多少个
    
    
    //通过是否被选的cell来确定选择的个数

    
    NSInteger numse=0;
    
//     float zonggongM=0;//总共的金额
    NSDecimalNumber *zonggongM = [[NSDecimalNumber alloc] initWithString:@"0"];//总金额
    
    for (int i=0; i<arrayList.count; i++) {
        
        MyOrderData *order=[[MyOrderData alloc]initWith:arrayList[i]];
        
        
            if ([order.isSelected isEqualToString:@"true"]) {
               
                numse++;
                NSDecimalNumber *everyDM = [[NSDecimalNumber alloc] initWithString:[NSString stringWithFormat:@"0"]];
                NSDecimalNumber *salem = [[NSDecimalNumber alloc] initWithString:[NSString stringWithFormat:@"%@",order.total_sales]];
                NSDecimalNumber *short_amount = [[NSDecimalNumber alloc] initWithString:[NSString stringWithFormat:@"%@",order.short_amount]];
                NSDecimalNumber *outbound_amount = [[NSDecimalNumber alloc] initWithString:[NSString stringWithFormat:@"%@",order.outbound_amount]];
                NSDecimalNumber *discount_amount = [[NSDecimalNumber alloc] initWithString:[NSString stringWithFormat:@"%@",order.discount_amount]];
        
                everyDM=[salem decimalNumberByAdding:short_amount];
                everyDM=[everyDM decimalNumberByAdding:outbound_amount];
                everyDM=[everyDM decimalNumberBySubtracting:discount_amount];
                
                zonggongM=[zonggongM decimalNumberByAdding:everyDM];
                
//                float salem=order.total_sales.floatValue;
//                zonggongM=zonggongM+salem;
             
            }
            
            
        }
    
    
    if (numse==arrayList.count) {
        isQX=@"true";
    }else{
    
        isQX=@"false";
    }
    
    if ([isQX isEqualToString:@"true"]) {
        
        [quanxuanBUt setBackgroundImage:[UIImage imageNamed:@"ic_apply_quality_selected"] forState:UIControlStateNormal];
        
    }else{
        
        [quanxuanBUt setBackgroundImage:[UIImage imageNamed:@"ic_radio_btn_normal"] forState:UIControlStateNormal];
    }

    
    NSString *butstr;
    if (numse==0) {
        butstr=[NSString stringWithFormat:@"结算"];
    }else{
        butstr=[NSString stringWithFormat:@"结算(%ld)",(long)numse];
    }
    
    [jiesuanBUt setTitle:butstr forState:UIControlStateNormal];
    
    //设定金额
    NSString *zgM=[NSString stringWithFormat:@"￥%@元",[NSString notRounding:zonggongM afterPoint:2]];
    hejiMoney.text=zgM;

    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
